<?php
class ModulePaymentOgz extends ModulePayment
{

    const PAYMENT_STATUS_DECLINE    = 3;
    const PAYMENT_STATUS_REFUND     = 4;
    const PAYMENT_STATUS_CHARGEBACK = 5;
    const PAYMENT_STATUS_DISPUTE    = 6;

    /**
     * @var ModuleSnsOgz
     */
    private $moduleSns;

    /**
     * @see ModulePayment::__construct()
     */
    public function __construct($userId, $platform)
    {
        parent::__construct($userId, $platform);
        $this->moduleSns = ModuleSnsFactory::init(null, ModuleSnsConst::PFVK);
    }

    /**
     * @see ModulePayment::completeOrder()
     *
     * @return string | array(
     *  int $userId,
     *  ModulePaymentOrderVo $order
     *  array $paymentSetting
     * )
     */
    public function completeOrder()
    {
        /**
         * array (
         *  'platform' => 'vk',     // 平台名
         *  'uid' => '30635',       // 玩家 ogz 平台id
         * 'sn_uid' => '318925326', // 玩家 实际 平台id
         * 'app_id' => '34',        // ogz 平台app id
         * 'sn_app_id' => '5584645',// 实际平台 app id
         * 'tid' => '2051',         // 交易id
         * 'sn_tid' => '1149518',   // 实际平台交易id
         * 'item' => '21',          // 物品id
         * 'price' => '1.0',        // 价格
         * 'currency' => 'VKVOTE',  // we use VKVOTE for vk, OKCRED for ok and MMCRED for mm now
         * 'amount' => '1',
         * 'idata' => '{}',
         * 'tdata' => '', // extra string eg: '{"extra":activityId,"type":activityType}',
         * 'created_at' => '1472559176',
         * 'time' => '1472559176',
         * 'sig' => 'fc44c03e7e428c4837ca44db735a10d9',
         * )
         * ------------------------
         * 完成支付的返回结果
         * array(
         *      'viewer_id': 用户平台UID,
         *      'res' => 真实平台订单id
         *      )
         * )
         */

        $input = SzParam::getWholePost();
        SzLogger::get()->debug('$input:' .var_export($input, true));

        // js callback
        if (SzUtility::checkArrayKey('res', $input)) {
            SzLogger::get()->debug('js callback res:'  .var_export($input, true));
            $userId = $this->moduleSns->portPlayerUserId($input['viewer_id']);
            $profile = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
            if (is_null($profile)) {
                return 100;
            }

            // 判断服务器是否维护中
            $appConfig = SzConfig::get()->loadAppConfig('app');
            if ($appConfig['MAINTENANCE']) {
                return 100;
            }

            /**
             * @var ModulePaymentOrderVoList $orderList
             * @var ModulePaymentOrderVo $order
             */
            $orderList = SzPersister::get()->getVoList(null, ModulePaymentConst::ORM_NAME_PAYMENT_ORDER, $userId);
            $latestOrder = null;
            $orderArray = $orderList->getList();
            krsort($orderArray);
            foreach ($orderArray as $order) {
                if ($order->getPlatformToken() == $input['res']) {
                    SzLogger::get()->debug('$latestOrder = $order;');
                    $latestOrder = $order;
                    break;
                }

                // platformToken 可能未知原因未更新，取最后一个订单
                if ($latestOrder == null) {
                    SzLogger::get()->debug('$latestOrder = null');
                    $latestOrder = $order;
                }
            }

            return array($userId, $latestOrder, null, true);
        }

        // 组织参数
        $sig = null;
        $str = '';
        if (SzUtility::checkArrayKey('sig', $input)) {
            $sig = $input['sig'];
            unset($input['sig']);
            ksort($input);
            foreach ($input as $k => $v) {
                $str .= $k.'='.$v;
            }
        }

        // 签名验证
        $payTokenConfig = ModuleSnsFactory::init(null, ModuleSnsConst::PFOGZ)->loadSnsSetting('appSecret');
        if ($sig != md5($str.$payTokenConfig['value'])) {
            SzLogger::get()->debug('ogz:501');
            return 501;
        } else {
            $return = $this->completeOrderRealtimeUpdate($input);
            return $return;
        }
    }


    /**
     * Complete the payment from ogz realtime update.
     *
     * array (
     * 'platform' => 'vk',     // 平台名
     * 'uid' => '30635',       // 玩家 ogz 平台id
     * 'sn_uid' => '318925326', // 玩家 实际 平台id
     * 'app_id' => '34',        // ogz 平台app id
     * 'sn_app_id' => '5584645',// 实际平台 app id
     * 'tid' => '2051',         // 交易id
     * 'sn_tid' => '1149518',   // 实际平台交易id
     * 'item' => '21',          // 物品id
     * 'price' => '1.0',        // 价格
     * 'currency' => 'VKVOTE',  // we use VKVOTE for vk, OKCRED for ok and MMCRED for mm now
     * 'amount' => '1',
     * 'idata' => '{}',
     * 'tdata' => '',  // extra string eg: '[activityId,activityType]',
     * 'created_at' => '1472559176',
     * 'time' => '1472559176',
     * 'sig' => 'fc44c03e7e428c4837ca44db735a10d9',
     * )
     * @return string | array(
     *      int $userId,
     *      ModulePaymentOrderVo $order
     *      array $paymentSetting
     * )
     */
    private function completeOrderRealtimeUpdate($input)
    {
        // 判断游戏角色是否创建
        $platformId = $input['uid'];
        $userId = $this->moduleSns->portPlayerUserId($platformId);
        $profile = SzPersister::get()->getVo($userId, ModuleProfileConst::ORM_NAME_PROFILE);
        if (is_null($profile)) {
            return 100;
        }

        // 判断服务器是否维护中
        $appConfig = SzConfig::get()->loadAppConfig('app');
        if ($appConfig['MAINTENANCE']) {
            return 100;
        }

        /**
         * @var ModulePaymentOrderVoList $orderList
         * @var ModulePaymentOrderVo $order
         */
        $orderList = SzPersister::get()->getVoList(null, ModulePaymentConst::ORM_NAME_PAYMENT_ORDER, $userId);
        foreach ($orderList->getList() as $order) {
            if ($order->getPlatformToken() == $input['sn_tid']) {
                return 100;
            }
        }

        // 未充值过，全新订单创建
        $paymentSetting = SzConfig::get()->loadAppConfig(ModulePaymentConst::CONFIG_PAYMENT, $input['item'], true);

        // TODO OGZ 平台修改实际的礼包？
        // extra info [activityId, activityType]
        $extra = array();
        if (isset($input['tdata'])) {
            $extra = json_decode($input['tdata']);
            // 30美金礼包活动需要替换 实际的礼包
            list($activityId, $activityType) = $extra;
            if ($activityType == GameConst::ACTIVITY_TYPE_FEEDBACK) {
                $paymentSetting = ActivityFeedbackService::get()->updateOgzPack($activityId, $paymentSetting);
            }
        }
        $order = $this->createOrder($userId, $paymentSetting, $input['sn_tid'], $extra, true);

        // 计算充值数量与付费价格
        $quantity = 1;
        $paymentPrice = $paymentSetting['price'] * $quantity;

        $order = $this->completeOrderAndSupplyResources($userId, $order, $paymentSetting, $quantity);
        $order->setPrice($paymentPrice);
        $orderList->updateElement($order->getOrderId(), $order);
        SzPersister::get()->setVoList($orderList);

        return array($userId, $order, $paymentSetting, false);
    }


    /**
     * @see ModulePayment::completeOrderReturnValue()
     */
    public function completeOrderReturnValue($result)
    {
        // 返回结构
        $return = null;
        if (is_array($result)) {
            list(, $order, $paymentSetting, $isAlreadyComplete) = $result;

            SzLogger::get()->debug('order:' . var_export($order, true));
            if ($isAlreadyComplete) {
                // js callback
                return $order;
            } else {
                if (!is_null($order)
                    && $order instanceof ModulePaymentOrderVo) {
                    $return = array(
                        'success' => true,
                        'code' => 101,
                        'order_id' => $order->getPlatformToken(),
                        'app_order_id' => $order->getOrderId(),
                    );
                } else {
                    $return = array(
                        'success' => false,
                        'code' => 500,
                        'message' => 'payment error:' . var_export($result, true),
                        'critical' => true
                    );
                }
                return json_encode($return);
            }

        } else {
            $return = array(
                'success' => false,
                'code' => 500,
                'message' => 'payment error:' . var_export($result, true),
                'critical' => true
            );
            return json_encode($return);
        }
    }

    /**
     * @see ModulePayment::repairOrder()
     */
    public function repairOrder($userId, $orderInfo)
    {
    }
}